package com.lianxueda.drawing.controller;


import com.lianxueda.drawing.common.R;
import com.lianxueda.drawing.domain.dto.CourseQueryDTO;
import com.lianxueda.drawing.domain.dto.CourseSaveDTO;
import com.lianxueda.drawing.domain.pojo.*;
import com.lianxueda.drawing.domain.vo.PageVO;
import com.lianxueda.drawing.mapper.CheckingInMapper;
import com.lianxueda.drawing.mapper.CourseStudentMapper;
import com.lianxueda.drawing.mapper.StudentsMapper;
import com.lianxueda.drawing.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 29264
 */
@RestController
@RequestMapping("/api/course")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "课程管理模块")
public class CourseController {

    private final CoursesService coursesService;
    private final ClassCoursesService classCoursesService;
    private final CourseStudentMapper courseStudentMapper;
    private final StudentsMapper studentsMapper;
    private final ClassService classService;
    private final CheckingInMapper checkingInMapper;
    //增加
    @PostMapping("/add")
    @Operation(summary = "新增课程")
    public R save(@RequestBody CourseSaveDTO courseSaveDTO){
        Courses courses = new Courses();
        BeanUtils.copyProperties(courseSaveDTO,courses);
        //如果课程的总次数没有值，则默认20
        if (courseSaveDTO.getCount() == null){
            courses.setCount(20);
        }
        courses.setRemainCount(courseSaveDTO.getCount());
        courses.setEvaluation("暂无");
        coursesService.save(courses);
        //将新增的课程id返回
        Integer courseId = courses.getId();
        if (courseId != null){
            String className = courseSaveDTO.getClassName();
            //根据className查询classId
            Integer classId = classService.getClassIdByName(className);

           //将class_id与courseId插入到class_courses表中
            classCoursesService.addCourseForClass(classId,courseId);
        }
        return R.suc("新增课程成功");
    }

    @PostMapping("/update")
    @Operation(summary = "更新课程")
    public R update(@RequestBody CourseSaveDTO courseSaveDTO) {
        // 创建并设置 Courses 实体类
        Courses courses = new Courses();
        BeanUtils.copyProperties(courseSaveDTO, courses);

        // 更新 courses 表中的记录
        boolean updateCourseResult = coursesService.updateById(courses);

        // 检查课程更新是否成功
        if (!updateCourseResult) {
            return R.fail("更新课程失败");
        }

        // 获取课程 ID
        Integer courseId = courseSaveDTO.getId();
        if (courseId == null) {
            return R.fail("课程 ID 为空，无法更新班级课程关系");
        }

        // 根据班级名称获取班级 ID
        String className = courseSaveDTO.getClassName();
        Integer classId = classService.getClassIdByName(className);

        // 如果班级 ID 为空，返回错误信息
        if (classId == null) {
            return R.fail("班级名称无效，未找到对应的班级 ID");
        }

        // 创建 ClassCourses 实体类并设置相关属性
       //根据courseId在class_courses表中更新class_id

        classCoursesService.updataClassIdByCourseId(classId, courseId);
        // 返回成功信息
        return R.suc("更新课程成功");
    }


    @DeleteMapping("/delect")
    @Operation(summary = "删除课程")
    public R delete(@Parameter Integer id){
        coursesService.removeById(id);
        return R.suc("删除课程成功");
    }

    @DeleteMapping("/deletes")
    @Operation(summary = "批量删除课程")
    public R deleteBatch(@RequestBody  Integer[] ids){
        coursesService.removeByIds(Arrays.asList(ids));
        return R.suc("批量删除课程成功");
    }


    @PostMapping("/pageList")
    @Operation(summary = "分页查询课程")
    public R pageList(@RequestBody CourseQueryDTO courseQueryDTO){
        PageVO pageVo = coursesService.searchPage(courseQueryDTO);
        return R.suc(pageVo);
    }

    //查询所有的课程名称，去除重复的班级名称
    @GetMapping("/getCourseName")
    @Operation(summary = "查询所有的课程名称")
    public R getCourseName() {
        // 假设 Course 有一个名为 courseName 的字段
        List<String> uniqueCourseNames = coursesService.list().stream()
                .map(Courses::getName) // 提取每个课程的名称
                .distinct() // 去除重复的课程名称
                .toList(); // 收集结果到 List 中

        return R.suc(uniqueCourseNames);
    }



    @GetMapping("/listAll")
    @Operation(summary = "获取所有课程及对应课表")
    public R getAllCoursesWithSchedules() {
        List<Courses> all = coursesService.getAllCoursesWithSchedules();
        return R.suc(all);
    }


//    @GetMapping("/getStudentsById")
//    @Operation(summary = "根据课程id获取学生对象列表")
//    public R getStudentsById(@Parameter Integer courseId){
//        // 根据courseId查询关联的student_id列表
//        List<Integer> studentIds = courseStudentMapper.getStudentIdsByCourseId(courseId);
//
//
//        // 如果studentIds为空，直接返回null
//        if (studentIds == null || studentIds.isEmpty()) {
//            return R.suc(null);
//        }
//
////        // 根据student_id列表查询students对象
////        List<Students> students = studentsMapper.getStudentsByIds(studentIds);
//        // 根据 student_id 列表查询 students 对象及其对应的 status
//        List<Students> students = studentsMapper.getStudentsByIdsWithStatus(studentIds);
//
//        // 对每个 student 对象检查 status 字段是否为 0，如果是则使用 courseStatus
//        for (Students student : students) {
//            if (student.getStatus() == 0) {
//                student.setStatus(student.getStatus());
//            }
//        }
//        // 返回学生对象列表
//        return R.suc(students);
//    }


    @GetMapping("/getStudentsById")
    @Operation(summary = "根据课程id和课表id获取学生对象列表")
    public R getStudentsById(@Parameter Integer courseId, @Parameter Integer schedelesId) {
        // 根据courseId查询关联的student_id列表
        List<Integer> studentIds = courseStudentMapper.getStudentIdsByCourseId(courseId);

        // 如果studentIds为空，直接返回null
        if (studentIds == null || studentIds.isEmpty()) {
            return R.suc(null);
        }

        // 根据 student_id 列表、courseId 和 schedelesId 查询 students 对象及其对应的 status
        List<Students> students = studentsMapper.getStudentsByIdsWithStatus(studentIds, courseId, schedelesId);

        // 返回学生对象列表
        return R.suc(students);
    }


    //根据班级id查找学生
    @GetMapping("/getStudentsByCourseId")
    @Operation(summary = "根据课程id获取学生对象列表")
    public R getStudentsByCourseId(@Parameter Integer courseId) {
        // 根据课程ID查询所有学生ID
        List<Integer> studentIds = courseStudentMapper.selectIdsById(courseId);

        // 根据学生ID查询学生信息
        List<Students> students = studentsMapper.selectByIds(studentIds);

        // 根据课程ID和学生ID查询考勤状态
        List<CheckingIn> checkingInRecords = checkingInMapper.selectByCourseIdAndStudentIds(courseId, studentIds);

        // 将考勤状态设置到学生对象中
        Map<Integer, Integer> statusMap = new HashMap<>();
        for (CheckingIn record : checkingInRecords) {
            statusMap.put(record.getStudentId(), record.getState());
        }

        for (Students student : students) {
            // 获取学生ID并查找其考勤状态
            Integer status = statusMap.getOrDefault(student.getId(), 0);
            student.setStatus(status);
        }

        return R.suc(students);
    }


}
